# -*- coding: utf-8 -*-
from datetime import datetime

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.interval import IntervalTrigger

from email_operation import operation as email
from get_ip_address import GetIPAddress
from logger import logger
from config import config


g = GetIPAddress()


class MailChecker():
    def __init__(self):
        # 已经回复过的IP
        self.address_replied = []
        """:type : list[(str, datetime)]"""

    def run(self):
        email.receive()
        count = 0
        this_time_replied = []
        for to_reply in email.to_reply:
            # 检查没有回复过，且同一次不对一个邮箱发送的多封请求邮件进行重复回复
            if to_reply not in self.address_replied:
                to_replay_address = to_reply[0]
                if to_replay_address not in this_time_replied:
                    email.send(to_replay_address, 'Auto Response Current IP', g.current_ip)
                    logger.info('发送给：' + to_replay_address)
                    count += 1
                self.address_replied.append(to_reply)
                this_time_replied.append(to_replay_address)
        return count


mail_checker = MailChecker()


def check_mail():
    logger.info('检查邮件...')
    send_count = mail_checker.run()
    logger.info('检查邮件结束，共发送：%d' % send_count)


def check_ip():
    """
    定时检查IP
    :return:
    :rtype:
    """
    g.get_ip()
    logger.info('获取新IP：%s' % g.current_ip)

    if g.current_ip != g.old_ip:
        if g.old_ip is not None:
            email.send(config.ip_changed_to, 'IP地址改变', 'date: %s, old: [%s] --> new: [%s]' % (datetime.now(), g.old_ip, g.current_ip))
        from dnspod_operation import operation as dns_pod

        ip = dns_pod.get_vpn_record_ip()
        if ip != g.current_ip:
            try:
                k = dns_pod.update_vpn_record(g.current_ip)
                msg = '域名解析已更新', 'date: %s, old: [%s] --> new: [%s] + \n %s' % (datetime.now(), ip, g.current_ip, k)
                print(msg)
                email.send(config.ip_changed_to, '域名解析已更新', msg)
            except Exception as e:
                logger.fatal(e)
    else:
        logger.info('IP没有变化')


scheduler = BlockingScheduler()
scheduler.add_job(check_ip, trigger=IntervalTrigger(seconds=config.interval))
scheduler.add_job(check_mail, trigger=IntervalTrigger(seconds=config.interval))
scheduler.start()